package com.wei.czz.framework.blog.helper;

import com.wei.czz.common.constant.EntityConstant;
import com.wei.czz.common.constant.RedisConstant;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.common.utils.TimeUtils;
import com.wei.czz.framework.blog.entity.BlogAuditUserConfigEntity;
import com.wei.czz.framework.blog.entity.BlogAuditUserStatEntity;
import com.wei.czz.framework.blog.service.*;
import com.wei.czz.framework.common.handler.redis.RedisStringHandler;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2025-02-24 21:17:46
 * className: BlogAuditHelper 博客审核帮助类
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class BlogAuditHelper {

    private static final Logger log = LoggerFactory.getLogger(BlogAuditHelper.class);

    private final BlogAuditService blogAuditService;

    private final BlogAuditAssignService blogAuditAssignService;

    private final BlogAuditGroupService blogAuditGroupService;

    private final BlogAuditGroupUserService blogAuditGroupUserService;

    private final BlogAuditReminderService blogAuditReminderService;

    private final BlogAuditUserConfigService blogAuditUserConfigService;

    private final BlogAuditUserStatService blogAuditUserStatService;

    private final RedisStringHandler redisStringHandler;

    private final RedissonClient redissonClient;

    /**
     * 获取博客审核用户配置
     * @param userId 用户主键
     * @return 博客审核用户配置
     */
    public BlogAuditUserConfigEntity getBlogAuditUserConfig(Long userId) {
        // 获取操作用户
        Optional<UserPo> optional = SecurityUtils.userPoOptional();

        String lockKey = RedisConstant.LOCK + EntityConstant.BLOG_AUDIT_USER_CONFIG + RedisConstant.SPLIT + userId;
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        log.info("获取博客审核用户配置，加锁成功。lockKey={}", lockKey);

        try {
            /*
                从数据库中获取博客审核用户配置
             */
            List<BlogAuditUserConfigEntity> blogAuditUserConfigList = blogAuditUserConfigService.findList(Collections.singletonList(userId));
            if (blogAuditUserConfigList.isEmpty()) {
                log.info("博客审核用户配置不存在。userId={}", userId);
                throw new CzzException("博客审核用户配置不存在，请务必及时处理");
            }

            BlogAuditUserConfigEntity blogAuditUserConfig = blogAuditUserConfigList.get(0);

            /*
                判断用户配置是否超过一个月
                超过一个月则备份用户配置
             */
            Date date = new Date();
            if (TimeUtils.betweenMonths(blogAuditUserConfig.getKpiDate(), date) >= 1) {
                /*
                    更新博客审核用户配置
                 */
                BlogAuditUserConfigEntity updateBlogAuditUserConfig = new BlogAuditUserConfigEntity();
                updateBlogAuditUserConfig.setId(blogAuditUserConfig.getId())
                        .setKpiDate(date)
                        .setAuditNum(CommonEnum.ZERO.getValue())
                        .setClaimNum(CommonEnum.ZERO.getValue());
                blogAuditUserConfigService.saveOrEdit(updateBlogAuditUserConfig);

                /*
                    保存博客审核用户统计
                 */
                BlogAuditUserStatEntity saveBlogAuditUserStat = new BlogAuditUserStatEntity();
                saveBlogAuditUserStat.setUserId(userId)
                        .setKpi(blogAuditUserConfig.getKpi())
                        .setKpiDate(blogAuditUserConfig.getKpiDate())
                        .setAuditNum(blogAuditUserConfig.getAuditNum())
                        .setClaimNum(blogAuditUserConfig.getClaimNum());
                blogAuditUserStatService.saveOrEdit(saveBlogAuditUserStat);

                // 更新返回对象数据
                blogAuditUserConfig.setKpiDate(TimeUtils.getMonthStartDate(date))
                        .setAuditNum(CommonEnum.ZERO.getValue())
                        .setClaimNum(CommonEnum.ZERO.getValue())
                        .setUpdateTime(date)
                        .setUpdateUser(optional.map(UserPo::getUsername).orElse("系统"))
                        .setUpdateUserId(optional.map(UserPo::getUserId).orElse(CommonEnum.ZERO.getLongValue()));
            }

            return blogAuditUserConfig;
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                // 解锁
                lock.unlock();
            }
        }

//        /*
//            从缓存中获取博客审核用户配置
//         */
//        String redisKey = RedisConstant.STRING + EntityConstant.BLOG_AUDIT_USER_CONFIG + RedisConstant.SPLIT + userId;
//        BlogAuditUserConfigEntity blogAuditUserConfig = redisStringHelper.get(redisKey);
//        if (Objects.nonNull(blogAuditUserConfig)) {
//            log.info("从缓存获取到博客审核用户配置。{}", blogAuditUserConfig);
//            return blogAuditUserConfig;
//        }
//
//        String lockKey = RedisConstant.LOCK + EntityConstant.BLOG_AUDIT_USER_CONFIG + RedisConstant.SPLIT + userId;
//        RLock lock = redissonClient.getLock(lockKey);
//        boolean bool = lock.tryLock();
//        log.info("获取博客审核用户配置，尝试加锁完成。lockKey={} bool={}", lockKey, bool);
//        if (!bool) {
//            lock.lock();
//            log.info("获取博客审核用户配置，加锁成功");
//
//            // double check
//            blogAuditUserConfig = redisStringHelper.get(redisKey);
//            if (Objects.nonNull(blogAuditUserConfig)) {
//                log.info("double check->从缓存获取到博客审核用户配置。{}", blogAuditUserConfig);
//                return blogAuditUserConfig;
//            }
//        }
//
//        try {
//            /*
//                从数据库中获取博客审核用户配置
//             */
//            List<BlogAuditUserConfigEntity> blogAuditUserConfigList = blogAuditUserConfigService.findList(Collections.singletonList(userId));
//            if (blogAuditUserConfigList.isEmpty()) {
//                log.info("博客审核用户配置不存在。userId={}", userId);
//                throw new CzzException("博客审核用户配置不存在，请务必及时处理");
//            }
//
//            blogAuditUserConfig = blogAuditUserConfigList.get(0);
//
//            // 缓存30分钟
//            redisStringHelper.set(redisKey, blogAuditUserConfig, 30, TimeUnit.MINUTES);
//
//            return blogAuditUserConfig;
//        } finally {
//            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
//                // 解锁
//                lock.unlock();
//            }
//        }
    }
}
